/**
 * 报表设计公司(2011)
 */
package com.reportgear.report.core.model.util;

import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import com.reportgear.report.model.ReportModel;
import com.reportgear.report.model.auxiliary.ColumnPropList;
import com.reportgear.report.model.auxiliary.ColumnRow;
import com.reportgear.report.model.auxiliary.RowPropList;
import com.reportgear.report.view.JWorksheet;
import com.reportgear.report.view.grid.selection.GridSelection;
import com.reportgear.report.view.grid.selection.Selection;
import com.reportgear.report.view.grid.util.Utils;

/**
 * 基础实用类
 * 
 * @deprecated
 * @version 1.0 2011-3-13
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since ANNCSR 2.0
 */
public class BaseUtils {
	private static final Logger logger = LoggerFactory.getLogger(BaseUtils.class.getName());

	private static DocumentBuilderFactory documentBuilderFactory = null;

	// // 初始化XML文档构建工厂
	// static {
	// documentBuilderFactory = DocumentBuilderFactory.newInstance();
	// documentBuilderFactory.setNamespaceAware(false);
	// documentBuilderFactory.setValidating(false);
	// documentBuilderFactory.setIgnoringComments(true);
	// }
	//
	//
	//	
	//	
	// /**
	// * 解析XML
	// *
	// * @param stream
	// * Xml数据流
	// * @return Xml文档
	// * @throws Exception
	// * 解析异常
	// */
	// public static Document parseXML(InputStream stream) throws Exception {
	// return parseXML(stream, null);
	// }
	//
	// /**
	// * 解析XML
	// *
	// * @param stream
	// * 数据流
	// * @param charsetName
	// * 字符集名称
	// * @return Xml文档
	// * @throws Exception
	// * 解析异常
	// */
	// public static Document parseXML(InputStream stream, String charsetName)
	// throws Exception {
	// InputStreamReader reader;
	// if (charsetName == null) {
	// reader = new InputStreamReader(stream);
	// } else {
	// reader = new InputStreamReader(stream, charsetName);
	// }
	// return parseXML(reader);
	// }
	//
	// /**
	// * 解析XML
	// *
	// * @param reader
	// * 阅读齐
	// * @return Xml文档
	// * @throws Exception
	// * 异常
	// */
	// public static Document parseXML(Reader reader) throws Exception {
	// DocumentBuilder domBuilder = documentBuilderFactory.newDocumentBuilder();
	// InputSource is = new InputSource(reader);
	//
	// return domBuilder.parse(is);
	// }

	/**
	 * 图片转化成缓冲图片
	 * 
	 * @param image
	 *            图片
	 * @return 缓冲
	 */
	public static BufferedImage toBufferedImage(Image image) {
		if (image instanceof BufferedImage) {
			return ((BufferedImage) image);
		}

		image = new ImageIcon(image).getImage();
		int transparency = hasAlpha(image) ? Transparency.BITMASK : Transparency.OPAQUE;
		BufferedImage bufferedImage = null;
		GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
		try {
			GraphicsDevice gd = genv.getDefaultScreenDevice();
			GraphicsConfiguration gcf = gd.getDefaultConfiguration();
			bufferedImage = gcf.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
		} catch (HeadlessException ex) {
			logger.warn(ex.getMessage());
		}
		if (bufferedImage == null) {
			bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), transparency);
		}

		Graphics2D g2 = bufferedImage.createGraphics();
		g2.drawImage(image, 0, 0, null);
		g2.dispose();

		return bufferedImage;
	}

	/**
	 * 图片是否包含alpha信息
	 * 
	 * @param image
	 *            图片
	 * @return 图片是否包含alpha信息
	 */
	private static boolean hasAlpha(Image image) {
		if (image instanceof BufferedImage) {
			return ((BufferedImage) image).getColorModel().hasAlpha();
		}
		PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
		try {
			pg.grabPixels();
		} catch (InterruptedException ex) {
			logger.warn(ex.getMessage());
		}

		ColorModel cm = pg.getColorModel();

		return cm.hasAlpha();
	}

	/**
	 * 获取网格选择行Index列表
	 * 
	 * @param gridSelection
	 *            网格选择集
	 * @return 行Index列表
	 */
	public static List<Integer> getGridSelectionRowIndex(GridSelection gridSelection) {
		List<Integer> result = new ArrayList<Integer>();
		for (Selection sel : gridSelection.getCellSelectionList()) {
			int row = sel.getRow();
			for (int j = 0, len = sel.getRowSpan(); j < len; j++) {
				int k = row + j;
				if (result.contains(k)) {
					continue;
				}

				result.add(k);
			}
		}

		Collections.sort(result);

		return result;
	}

	/**
	 * 获取网格选择列Index列表
	 * 
	 * @param gridSelection
	 *            网格选择集
	 * @return 列Index列表
	 */
	public static List<Integer> getGridSelectionColumnIndex(GridSelection gridSelection) {
		List<Integer> result = new ArrayList<Integer>();
		for (Selection sel : gridSelection.getCellSelectionList()) {
			int column = sel.getColumn();
			for (int j = 0, len = sel.getColumSpan(); j < len; ++j) {
				int k = column + j;
				if (result.contains(k)) {
					continue;
				}

				result.add(k);
			}
		}
		Collections.sort(result);

		return result;
	}

	public static String convertColumnRowToCellString(ColumnRow columnRow) {
		if (columnRow == null) {
			return "";
		}
		return columnRow.toString();
	}

	public static ColumnRow convertCellStringToColumnRow(String cellString) {
		return ColumnRow.valueOf(cellString);
	}


	public static String addFileSeparator(String str) {
		if ((!(str.endsWith("/"))) && (!(str.endsWith("\\")))) {
			return str += File.separator;
		}
		return str;
	}

	public static byte[] getBytesFromIS(InputStream inputStream) throws IOException {
		ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
		int i = 0;
		while ((i = inputStream.read()) != -1) {
			arrayOutputStream.write(i);
		}
		return arrayOutputStream.toByteArray();
	}
}
